import sys
try:
    import pygtk
    pygtk.require('2.0')
except:
    pass
try:
    import gtk
    import gtk.glade
    gtk.gdk.threads_init()
except:
    sys.exit(1)

from utils.debug import *

class Gui:

    def __init__(self, gladefile, window, signal_dict={}):
        '''
        read *.glade, get its main window/dialog,
        then connect signals
        '''
        self.wTree = gtk.glade.XML('glade/%s.glade' % gladefile)
        self.window = self.widget(window)
        if self.window:
            self.autoconnect(signal_dict)
        else:
            error('Cannot create window!')
            sys.exit(1)
    
    def run(self):
        '''
        display the window/dialog
        '''
        gtk.main()
    
    def widget(self, name):
        '''
        Accessing widget
        '''
        return self.wTree.get_widget(name)
    
    def connect(self, widget, signal, func):
        '''
        Connecting signal with function
        '''
        widget.connect(signal, func)
    
    def autoconnect(self, d):
        '''
        Auto connect widgets' signals with specified functions
        given dictionary of signal-function pairs
        '''
        if isinstance(d, type({})):
            self.wTree.signal_autoconnect(d)
        else:
            error('Signal-function pair must be a dictionary!')
    
    def quit(self, widget):
        '''
        Delete temporary files and terminate the application
        '''
        gtk.main_quit()
